#include <iostream>
#include <vector>
#include "clio.h"

using namespace std;

class stl_file
{
public:
	stl_file(string filename)
	{
		_file = fopen(filename.c_str(), "rb");

		if(!_file)
			throw;
	}

	stl_file(vector<triangle3d> &tr) : _file(NULL)
	{
		triangles.insert(triangles.begin(), tr.begin(), tr.end());
		hdr.ntriangles = triangles.size();
		
	}

	void save(string filename)
	{
		FILE *__file = fopen(filename.c_str(), "wb");

		fwrite(&hdr, 1, sizeof(hdr), __file);
		cout << "writing " << hdr.ntriangles << " triangles in file" << endl;
		for(int i = 0; i < hdr.ntriangles; i++)
		{
			copy(triangles[i].points[0].coords, triangles[i].points[0].coords + 3, item.v1);
			copy(triangles[i].points[1].coords, triangles[i].points[1].coords + 3, item.v2);
			copy(triangles[i].points[2].coords, triangles[i].points[2].coords + 3, item.v3);
			item.normal[0] = 0.0;
			item.normal[1] = 0.0;
			item.normal[2] = 0.0;
			item.abc = rand();

			fwrite(&item, 1, sizeof(item), __file);

//			cout << "color " << triangles[i].color << endl;
		}
		fclose(__file);
	}

	void load()
	{
		if(!_file)
			throw;

		triangles.clear();

		fread(&hdr, 1, sizeof(hdr), _file);
		cout << hdr.ntriangles << " triangles in file" << endl;
		for(int i = 0; i < hdr.ntriangles; i++)
		{
			fread(&item, 1, sizeof(item), _file);
			triangle3d tmp;
			memcpy(tmp.points + 0, item.v1, sizeof(float) * 3);
			memcpy(tmp.points + 1, item.v2, sizeof(float) * 3);
			memcpy(tmp.points + 2, item.v3, sizeof(float) * 3);

			triangles.push_back(tmp);
		}

	}
	~stl_file()
	{
		if(_file)
			fclose(_file);
	}

private:
	FILE *_file;

#pragma pack(push, 1)

	struct stl_header
	{
		unsigned char hdr[80];
		unsigned long ntriangles;
	} hdr;

	struct stl_item
	{
		float normal[3];
		float v1[3];
		float v2[3];
		float v3[3];
		unsigned short abc;
	} item;

#pragma pack(pop)

public:	
	vector<triangle3d> triangles;

};

